from media.display import *
from media.media import *
from media.sensor import *
import time, gc


class Logo:
    def __init__(self, 
                 display_width=960, 
                 display_height=540, 
                 video_width=960, 
                 video_height=540, 
                 logo_path="/sdcard/images/001.jpg"):
        """
        初始化K230显示管理器
        
        参数:
            display_width: 显示屏宽度
            display_height: 显示屏高度
            video_width: 摄像头输出宽度
            video_height: 摄像头输出高度
            logo_path: Logo图片路径
        """
        # 显示和摄像头参数
        self.display_width = display_width
        self.display_height = display_height
        self.video_width = video_width
        self.video_height = video_height
        self.logo_path = logo_path
        
        # 初始化传感器和显示资源（延迟到start()方法中执行）
        self.sensor = None

    def draw_logo(self):
        self.start()
        
        # 显示Logo 3秒
        self.show_logo(duration=3)
        
        # 显示3帧摄像头画面（覆盖Logo）
        self.display_camera_frames(frame_count=3)

        self.stop()

    def _align_to_8(self, x):
        """将尺寸对齐到8的倍数（K230平台要求）"""
        return (x // 8) * 8

    def start(self):
        """初始化媒体资源（摄像头、显示屏）"""
        # 初始化摄像头
        self.sensor = Sensor()
        self.sensor.reset()
        
        # 配置摄像头通道（主通道+OSD通道）
        aligned_height = self._align_to_8(self.video_height)
        self.sensor.set_framesize(width=self.video_width, height=aligned_height, chn=CAM_CHN_ID_0)
        self.sensor.set_pixformat(Sensor.RGB888, chn=CAM_CHN_ID_0)
        
        self.sensor.set_framesize(width=self.video_width, height=aligned_height, chn=CAM_CHN_ID_2)
        self.sensor.set_pixformat(Sensor.RGBP888, chn=CAM_CHN_ID_2)
        
        # 初始化显示屏
        Display.init(Display.NT35516, 
                    width=self.display_width, 
                    height=self.display_height, 
                    to_ide=True, 
                    osd_num=1)
        
        # 初始化媒体管理器并启动摄像头
        MediaManager.init()
        self.sensor.run()

    def show_logo(self, duration=3):
        """显示Logo图片指定时间"""
        try:
            # 加载Logo图片
            logo_img = image.Image(self.logo_path)
            
            # 计算居中位置
            offset_x = (self.display_width - logo_img.width()) // 2
            offset_y = (self.display_height - logo_img.height()) // 2
            
            # 显示Logo
            Display.show_image(logo_img.to_rgb888(), offset_x, offset_y)
            print(f"显示Logo {duration}秒...")
            time.sleep(duration)
            
        except Exception as e:
            print(f"显示Logo失败: {e}")

    def display_camera_frames(self, frame_count=3):
        """显示指定帧数的摄像头画面（用于覆盖Logo）"""
        if not self.sensor:
            print("请先调用start()初始化资源")
            return
            
        try:
            # 显示指定帧数的摄像头画面
            for i in range(frame_count):
                img = self.sensor.snapshot()  # 获取摄像头帧
                # 显示画面（覆盖Logo）
                Display.show_image(img)
                time.sleep_ms(50)  # 短暂延时确保刷新
            print(f"已显示{frame_count}帧摄像头画面，Logo已覆盖")
            
        except Exception as e:
            print(f"显示摄像头画面失败: {e}")

    def stop(self):
        """释放所有媒体资源"""
        if self.sensor:
            self.sensor.stop()  # 停止摄像头
            time.sleep_ms(50)
        
        # 释放显示资源
        Display.deinit()
        MediaManager.deinit()
        self.sensor = None  # 清空传感器引用
        gc.collect()  # 回收内存
        print("资源已释放")

